package com.anxin.registerManagement.util.jwt;

import com.anxin.registerManagement.util.Const;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;

/**
 * @author 叶前呈
 * @date 2022/1/22 15:25
 */
public class JwtUtil {

    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 校验token是否正确
     *
     * @param token token
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(Const.secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            logger.info(jwt + ":-token is valid");
            return true;
        } catch (Exception e) {
            logger.info("The token is invalid{}", e.getMessage());
            return false;
        }
    }

    /**
     * 判断是否过期
     */
    public static boolean isExpire(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().getTime() < System.currentTimeMillis();
    }

    /**
     * 根据key获取token中包含的claim信息，也就是sign的时候传入的map中的信息
     *
     * @param key
     * @return
     */
    public static String getClaim(String token, String key) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(key).asString();
        } catch (JWTDecodeException e) {
            logger.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 签名生成token
     *
     * @param data 要携带的内容
     * @return 返回token
     */
    public static String sign(Map<String, String> data) {
        Date date = new Date(System.currentTimeMillis() + Const.expire);
        Algorithm algorithm = Algorithm.HMAC256(Const.secret);
        // 附带username信息
        JWTCreator.Builder builder = JWT.create();
        for (String key : data.keySet()) {
            builder.withClaim(key, data.get(key));
        }
        builder.withExpiresAt(date);
        return builder.sign(algorithm);
    }

    /**
     * 检验jwt有效性
     */
    public static boolean check(String jwt){
        // 检验有效性
        verify(jwt);
        // 检验是否过期
        return isExpire(jwt);
    }
}

